<template>
  <div class="filter-container">
    <el-radio-group v-model="activeTab" @change="filterRecords" size="small">
      <el-radio-button value="current">当前记录</el-radio-button>
      <el-radio-button value="history">历史存档</el-radio-button>
    </el-radio-group>
  </div>
  <el-empty description="暂无数据！请先去测评吧！" v-if="dataList.length === 0"/>
  <el-table v-loading="loading" :data="dataList" width="100%" v-else>
    <!-- 原有列保持不变 -->
    <el-table-column label="测评卷编号" align="center" prop="paperId"/>
    <el-table-column label="测评卷标题" align="center" prop="title"/>
    <el-table-column label="测评卷封面" align="center" prop="paperImage">
      <template #default="scope">
        <image-preview :src="scope.row.paperImage" alt="试卷封面" style="width: 100px; height: 100px;"/>
      </template>
    </el-table-column>

    <el-table-column label="开始时间" align="center" prop="startTime">
      <template #default="scope">
        {{ formatTime(scope.row.startTime) }}
      </template>
    </el-table-column>

    <el-table-column label="提交时间" align="center" prop="submitTime">
      <template #default="scope">
        {{ scope.row.submitTime ? formatTime(scope.row.submitTime) : '未提交' }}
      </template>
    </el-table-column>

    <el-table-column label="总耗时" align="center">
      <template #default="scope">
        <el-tag :type="getDurationTag(scope.row.totalTime).type">
          {{ getDurationTag(scope.row.totalTime).text }}
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column label="得分" align="center" prop="totalScore">
      <template #default="scope">
        <el-tag type="success">{{ scope.row.totalScore }} 分</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="记录状态" align="center">
      <template #default="scope">
        <el-tag :type="scope.row.delFlag === '0' ? 'success' : 'info'">
          {{ scope.row.delFlag === '0' ? '当前记录' : '历史记录' }}
        </el-tag>
      </template>
    </el-table-column>

    <!-- 操作列 -->
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="handleResult(scope.row)">查看详情</el-button>
        <el-button v-if="scope.row.delFlag === '0'" type="warning" size="small" @click="handleCompare(scope.row)">
          对比历史
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog
      v-model="compareDialogVisible"
      title="历史记录对比"
      width="50%"
      class="compare-dialog"
  >
    <el-table :data="compareRecordList">
      <template #empty>
        <div class="empty-box" v-if="compareRecordList.length === 0">
          <p style="color: #909399; margin-top: 10px;">暂无历史记录可对比</p>
        </div>
      </template>
      <el-table-column label="测评卷" prop="title"/>
      <el-table-column label="测评时间" prop="submitTime">
        <template #default="{row}">
          {{ formatTime(row.submitTime) }}
        </template>
      </el-table-column>
      <el-table-column label="得分" align="center" prop="totalScore">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.totalScore }} 分</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总耗时" align="center">
        <template #default="scope">
          <el-tag :type="getDurationTag(scope.row.totalTime).type">
            {{ getDurationTag(scope.row.totalTime).text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button @click="startCompare(row)">对比</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup>
import {getHistoryList} from "@/api/assessments/assessments.js";
import {getCurrentInstance, onMounted} from "vue";
import dayjs from "dayjs";
import ImagePreview from "@/components/ImagePreview/index.vue";

const {proxy} = getCurrentInstance()
const loading = ref(true);
const dataList = ref([]);
const examRecordList = ref([]);
const examPaperList = ref([]);
const activeTab = ref('current')

// 对比历史
const compareDialogVisible = ref(false)
const currentComparePaper = ref(null)
const compareRecordList = ref([])

const handleCompare = (currentRecord) => {
  // 使用examRecordList进行过滤
  compareRecordList.value = examRecordList.value
      .filter(
          (item) =>
              item.paperId === currentRecord.paperId &&
              item.id !== currentRecord.recordId &&
              item.delFlag !== "0"
      )
      .map((record) => {
        const paper = examPaperList.value.find((p) => p.id === record.paperId);
        return {
          recordId: record.id,
          paperId: paper.id,
          title: paper.title,
          submitTime: record.submitTime,
          totalScore: record.totalScore,
          totalTime: record.totalTime / 1000,
          delFlag: record.delFlag,
        };
      });

  currentComparePaper.value = currentRecord;
  compareDialogVisible.value = true;
};

const startCompare = (selectedRecord) => {
  proxy.$router.push({
    path: '/compare-result',
    query: {
      currentId: currentComparePaper.value.recordId,
      compareId: selectedRecord.recordId
    }
  })
}

const formatTime = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm');
};

const getDurationTag = (seconds) => {
  if (!seconds) return {type: 'info', text: '0分钟'}

  // 确保处理的是数字类型
  const totalSeconds = Number(seconds)
  const totalMinutes = Math.floor(totalSeconds / 60)
  const remainingSeconds = Math.floor(totalSeconds % 60) // 直接取整

  if (totalMinutes >= 60) {
    const hours = Math.floor(totalMinutes / 60)
    const mins = totalMinutes % 60
    return {
      type: 'warning',
      text: `${hours}小时${mins}分钟${remainingSeconds}秒`
    }
  }

  if (totalMinutes > 0) {
    return {
      type: 'success',
      text: `${totalMinutes}分钟${remainingSeconds}秒`
    }
  }

  return {
    type: 'primary',
    text: `${remainingSeconds}秒`
  }
}

function handleResult(row) {
  proxy.$router.push({
    path: '/result',
    query: {  // 使用 query 传参
      paperId: row.paperId,
      recordId: row.recordId, // 传递唯一记录ID
      delFlag: row.delFlag
    }
  })
}

// 加载测评历史记录
function loadHistoryList() {
  getHistoryList().then(res => {
    if (res.code === 200) {
      if (res.data.examRecordList.length > 0) {
        examPaperList.value = res.data.examPaperList;
        examRecordList.value = res.data.examRecordList;

        // 初始加载当前记录
        filterRecords('current')

        console.log("dataList", dataList.value)
        loading.value = false;
      } else {
        loading.value = false;
      }
    }
  })
}

// 记录过滤方法
function filterRecords(type) {
  dataList.value = examRecordList.value
      .filter(item => type === 'current' ? item.delFlag === '0' : item.delFlag !== '0')
      .map(record => {
        const paper = examPaperList.value.find(p => p.id === record.paperId)
        return {
          // 考试记录字段
          recordId: record.id,            // 记录唯一ID
          userId: record.userId,          // 用户ID
          submitTime: record.submitTime,  // 提交时间
          totalScore: record.totalScore,  // 总得分
          delFlag: record.delFlag,        // 记录状态（0=当前记录，2=历史记录）
          totalTime: Math.round(record.totalTime / 1000),

          // 试卷字段
          paperId: paper.id,              // 试卷ID
          title: paper.title,             // 试卷标题
          description: paper.description, // 试卷描述
          paperImage: paper.paperImage,   // 试卷封面
          questionTotal: paper.questionTotal, // 题目总数
          timeLimit: paper.timeLimit      // 考试时限（分钟）
        }
      })
}

onMounted(() => {
  loadHistoryList();
})
</script>

<style scoped lang="scss">
.filter-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  background: #f8f9fa;
  border-radius: 8px;

  :deep(.el-radio-group) {
    .el-radio-button {
      margin: 0 8px;

      &:first-child .el-radio-button__inner {
        border-radius: 4px 0 0 4px;
      }

      &:last-child .el-radio-button__inner {
        border-radius: 0 4px 4px 0;
      }
    }
  }
}

:deep(.compare-dialog) {
  .el-dialog__header {
    padding: 20px;
    background: linear-gradient(135deg, #fafbfc, #f1f3f5);
    border-radius: 8px 8px 0 0;

    .el-dialog__title {
      color: #2c3e50;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .el-dialog__body {
    padding: 20px;

    .el-table {
      border: 1px solid #ebeef5;
      border-radius: 8px;

      th {
        background-color: #f8f9fa !important;
        color: #606266;
        font-weight: 600;
      }

      td {
        transition: background-color 0.2s;
      }

      tr:hover td {
        background-color: #fafbfc !important;
      }
    }
  }

  .empty-box {
    padding: 40px 0;
    text-align: center;

    p {
      color: #909399;
      font-size: 14px;
      margin-top: 10px;
    }
  }
}

.filter-container {
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

:deep(.compare-dialog) {
  .el-dialog__header {
    background: linear-gradient(135deg, #f8f9fa, #e9ecef);
    border-radius: 8px 8px 0 0;

    .el-dialog__title {
      color: #2c3e50;
      font-weight: 600;
    }
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;

    th {
      background-color: #f8f9fa !important;
      color: #495057;
      font-weight: 600;
    }

    tr:hover td {
      background-color: #f1f3f5 !important;
    }

    .el-button {
      padding: 8px 15px;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
      }
    }
  }

  .el-pagination {
    margin-top: 20px;
    justify-content: center;
  }
}

</style>
